package utils
{
	import flash.text.TextFormat;	
	import flash.text.TextField;	
	import flash.text.TextFieldAutoSize;	
	import flash.events.Event;	
	import flash.system.System;	
	import flash.display.Sprite;
	import flash.utils.getTimer;

	public class FPSCounter extends Sprite
	{
		private var txt:TextField;
		private var last:uint = getTimer();
        private var ticks:uint = 0;
		private var oldFPS: int = 0;

		
		public function FPSCounter()
		{
			txt = new TextField();//Utils.createTextField();
			txt.selectable = false;
			txt.wordWrap = false;
			txt.autoSize = TextFieldAutoSize.LEFT;
			txt.antiAliasType = "normal";
			txt.background = true;
			txt.backgroundColor = 0xFFA500;			
		
			var txtFormat:TextFormat = new TextFormat();

			with (txtFormat){
				font = "_sans";
				color = 0xFFFFFF;							
				bold = true;
				size = 12;
				//selectable = false;
			}
			txt.defaultTextFormat = txtFormat;
			update();

			this.addChild(txt);
			//trace(">>>>>>>>>>>>>", stage.width)

			this.addEventListener(Event.ENTER_FRAME, update);
		}
		
		private function update(e:Event = null): void {
			if (stage!=null){
				//var mem:String = Utils.roundDec(Number( System.totalMemory / 1024 / 1024), 2) + " Mb";
				var mem:String = Number(System.privateMemory / 1024 / 1024).toFixed(2) + " Mb";
				txt.text = "Memory: " + mem;
				
				ticks++;
				var now:uint = getTimer();
				var delta:uint = now - last;
				var fps:Number;
				if (delta >= 1000) {
					//trace(ticks / delta * 1000+" ticks:"+ticks+" delta:"+delta);
					fps = ticks / delta * 1000;
					ticks = 0;
					last = now;
					oldFPS = fps;
				} else {
					fps = oldFPS;
				}
				
				//txt.text += "    " +  fps.toFixed(1) + " fps";
				txt.appendText("    " +  fps.toFixed(1) + " fps");
				
				//txt.x = stage.stageWidth - 180//txt.width;
				//txt.y = stage.stageHeight - txt.height;		
			}
		}
	}
}
